package org.orbroker

import java.sql._
import org.orbroker.exception._

private[orbroker] trait UpdateSession extends Executable with QuerySession {
  private def call[T](
    token: Token[T], parms: Seq[(String, Any)],
    keyHandler: Option[(T) ⇒ Unit],
    receivers: Seq[T ⇒ Boolean],
    outParmHandler: Option[(OutParms) ⇒ Unit]): Int = {
    val startTime = System.nanoTime
    val cstm = getCallStatement(token)
    try {
      val (sql, values, rowsUpdated, outParm) =
        cstm.call(token, this, toMap(parms), keyHandler, receivers, outParmHandler)
      callback.onSQL(token.id, sql, values, diffTimeInMicros(startTime))
      uncommittedChanges |= rowsUpdated > 0
      rowsUpdated
    } catch {
      case e: SQLException ⇒ throw evaluate(e)
    }
  }

  def callForUpdate(token: Token[_], parms: (String, Any)*): Int =
    call(token, parms, None, Seq.empty, None)

  def callForKeys[K](token: Token[K], parms: (String, Any)*)(keyHandler: K ⇒ Unit): Int = {
    call(token, parms, Some(keyHandler), Seq.empty, None)
  }
}
